<?php

namespace app\api\controller;

use app\api\service\UserToken;
use app\api\validate\TokenGet;
use app\common\controller\Send;
use app\api\service\Token as T2;

class Token
{
    use Send;

    /**
     * +-------------------------------------------------------------
     * | 通过前端传来的临时登录凭证 code 换取openid、session_key，
     * | 并返回登录token给前端
     * +-------------------------------------------------------------
     * @return array
     * @throws \think\Exception\DbException
     */
    public function getToken()
    {
        $code = $data['code'] = input('code');

        // 检测变量
        $validate = new TokenGet();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        // 登录获取openid跟session_key
        $userToken = new UserToken();
        $result = $userToken->login($code);

        // 登录失败返回
        if ($result['code'] != self::$okCode) {
            return self::sendResult($result['code'], [], $result['msg']);
        }

        // 发放登录token
        $return = $userToken->grantToken($result['data']);
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }

    /**
     * 刷新token
     * @return array
     */
    public function refresh()
    {
        $refreshToken = input('refreshToken');
        $userToken = new UserToken();
        $return = $userToken->refresh($refreshToken);
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }

    /**
     * app刷新token
     */
    public function refreshAppToken()
    {
        $refreshToken = input('refreshToken');
        
        $uid = cache($refreshToken);
        
        if(empty($uid)){
            return self::sendResult(102, [], '缓存过期请重新登录');
        }else{
            $token = T2::generateToken();
            cache($token, $uid, 86400);
            cache($refreshToken,null,2);//旧的token清除
            $refreshToken = T2::generateToken();
            cache($refreshToken,$uid,86400 * 2);
            $data['token'] = $token;
            $data['refreshToken'] = $refreshToken;
        }
        return self::sendResult(self::$okCode, $data,"ok");
    }


    
}